package com.exigenservices.practice.roadcompanion.server.dao;

import com.exigenservices.practice.roadcompanion.server.entity.Points;
import com.exigenservices.practice.roadcompanion.server.entity.UserRoutes;
import org.hibernate.HibernateException;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Konstantin
 * Date: 15.07.13
 * Time: 15:07
 * To change this template use File | Settings | File Templates.
 */
public class PointsDAOimpl implements PointsDAO {

    @PersistenceContext(unitName = "Points")
    private EntityManager entityManager;

    public PointsDAOimpl(EntityManager entityManager){
        this.entityManager = entityManager;
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void createPoint(Points point) throws Exception {
        try{
            entityManager.persist(point);

        } catch (HibernateException e){
            throw new Exception("Could not create point. " + e.getMessage());
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void updatePoint(Points point) throws Exception {
       try {
           Points p = entityManager.find(Points.class, point.getID());

           p = point;

       } catch (HibernateException e){
           throw new Exception("Could not update point" + e.getMessage());
       }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void deletePoint(Points point) throws Exception {
        try{
            entityManager.remove(point);

        } catch (HibernateException e){
            throw  new Exception("Could not delete point" + e.getMessage());
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<Points> getPoints(UserRoutes route) throws Exception {
        try{
            List<Points> points = entityManager.createQuery("select Points from Points where points.routeID = ?" + route.getID()).getResultList();

            return points;
        } catch (HibernateException e){
            throw new Exception("Could not find points" + e.getMessage());
        }
    }
}
